/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */
package com.hopes.bizz.poll.om.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopes.bizz.common.core.util.ListBeanUtils;
import com.hopes.bizz.poll.analy.dto.AnalyzeTrendDTO;
import com.hopes.bizz.poll.common.constant.OmConstant;
import com.hopes.bizz.poll.common.util.OmDataJsonUtils;
import com.hopes.bizz.poll.gis.dto.GisMonitorHisDTO;
import com.hopes.bizz.poll.gis.vo.GisAir;
import com.hopes.bizz.poll.gis.vo.GisWater;
import com.hopes.bizz.poll.om.dto.PollRtDataDTO;
import com.hopes.bizz.poll.om.entity.BaseOmDataEntity;
import com.hopes.bizz.poll.om.entity.PollDayEntity;
import com.hopes.bizz.poll.om.entity.PollRtDataEntity;
import com.hopes.bizz.poll.om.mapper.PollDayMapper;
import com.hopes.bizz.poll.om.service.PollDayService;
import com.hopes.bizz.poll.om.service.PollRtDataHisService;
import com.hopes.bizz.poll.om.service.PollRtDataService;
import com.hopes.bizz.poll.om.vo.PollRtDataVO;
import com.hopes.bizz.poll.pollaqi.entity.Aqi;
import com.hopes.boss.common.security.util.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 日监控数据历史
 *
 * @author pig
 * @date 2023-05-23 14:00:05
 */
@Service("pollDay")
public class PollDayServiceImpl extends ServiceImpl<PollDayMapper, PollDayEntity> implements PollDayService {
    @Autowired
    private PollRtDataService pollRtDataService;

    @Autowired
    private PollRtDataHisService pollRtDataHisService;

    @Override
    public void saveHJ212Data(BaseOmDataEntity omDataEntity, String data) {
        PollRtDataEntity pollRtDataEntity = new PollRtDataEntity();
        BeanUtils.copyProperties(omDataEntity, pollRtDataEntity);
        pollRtDataEntity.setDataType(OmConstant.DATA_TYPE_DAY);
        pollRtDataService.deleteByMonitorSiteIdAndDataType(pollRtDataEntity);
        pollRtDataService.save(pollRtDataEntity);

        PollDayEntity pollDayEntity = new PollDayEntity();
        BeanUtils.copyProperties(omDataEntity, pollDayEntity);
        this.deleteByMonitorSiteIdAndDataTime(omDataEntity);
        this.save(pollDayEntity);
    }


    @Override
    public List<PollDayEntity> uploadData(List<PollRtDataDTO> pollUploadDataList) {
        List<PollRtDataDTO> uniquePollUploadDataList = pollUploadDataList.stream()
                .distinct()
                .collect(Collectors.toList());
        List<BaseOmDataEntity> dataList = ListBeanUtils.copyListProperties(uniquePollUploadDataList, BaseOmDataEntity::new);
        List<PollDayEntity> OverwrittenData = new ArrayList<>();
        dataList.forEach(omDataEntity -> {
            // 计算WQI 水质 共用aqi字段
            Double wqi = computerWQI(omDataEntity.getMonitorSiteId(), omDataEntity.getDataJson());
            omDataEntity.setAqiData(wqi);
            omDataEntity.setOrgId(SecurityUtils.getOrgId());
            PollRtDataEntity pollRtDataEntity = new PollRtDataEntity();
            BeanUtils.copyProperties(omDataEntity, pollRtDataEntity);
            pollRtDataEntity.setDataType(OmConstant.DATA_TYPE_DAY);
            pollRtDataService.deleteByMonitorSiteIdAndDataType(pollRtDataEntity);
            pollRtDataService.save(pollRtDataEntity);
            PollDayEntity pollDayEntity = new PollDayEntity();
            BeanUtils.copyProperties(omDataEntity, pollDayEntity);
            //判断覆盖
            QueryWrapper<PollDayEntity> queryWrapper = new QueryWrapper<PollDayEntity>();
            queryWrapper.eq("monitor_site_id",pollDayEntity.getMonitorSiteId());
            queryWrapper.eq("data_time",pollDayEntity.getDataTime());
            List<PollDayEntity> querylist = this.list(queryWrapper);
            OverwrittenData.addAll(querylist);
            //数据处理
            this.deleteByMonitorSiteIdAndDataTime(omDataEntity);
            this.save(pollDayEntity);
        });
        return OverwrittenData;
    }

    private Double computerWQI(Long id, JSONObject data) {
        try {
            // 计算WQI的值 水质 共用aqi字段
            Aqi wqi = pollRtDataHisService.calculateWQI(data);
            if (ObjectUtil.isNotEmpty(wqi)) {
                return wqi.getAqi();
            }
            return null;
        } catch (Exception e) {
            log.error("天WQI计算出错");
            return null;
        }
    }
    @Override
    public void deleteByMonitorSiteIdAndDataTime(BaseOmDataEntity omDataEntity) {
        this.baseMapper.deleteByMonitorSiteIdAndDataTime(omDataEntity);
    }

    @Override
    public List<BaseOmDataEntity> listOmDayList(AnalyzeTrendDTO analyzeTrendDTO, List<String> factorCodeList) {
        final List<BaseOmDataEntity> result = new ArrayList<>();
        // 1、根据选择的站点和时间范围查询数据
        final List<BaseOmDataEntity> pollDayEntityList = this.baseMapper.listOmDayList(analyzeTrendDTO);
        // 2、数据过滤处理需要展示的因子数据
        for (BaseOmDataEntity baseOmDataEntity : pollDayEntityList) {
            final JSONObject dataJson = JSONObject.parseObject(JSON.toJSONString(baseOmDataEntity.getDataJson()));

            OmDataJsonUtils.filterFactorCode(dataJson, factorCodeList);

            if (MapUtil.isNotEmpty(dataJson)) {
                result.add(baseOmDataEntity);
            }
        }
        return result;
    }

    @Override
    public List<BaseOmDataEntity> listOmDayByDateRangeAndSite(Date beginTime, Date endTime, List<Long> monitorSiteList) {
        return this.baseMapper.listOmDayByDateRangeAndSite(beginTime, endTime, monitorSiteList);
    }

    @Override
    public List<PollRtDataVO> queryByTimeAndMonitor(PollRtDataDTO pollRtDataDTO) {
        return baseMapper.queryByTimeAndMonitor(pollRtDataDTO);
    }

    @Override
    public Page<PollRtDataVO> selectPageByMonitorSiteIdAndDataType(Page<PollRtDataVO> page, PollRtDataDTO pollRtDataDTO) {
        return baseMapper.selectPageByMonitorSiteIdAndDataType(page, pollRtDataDTO);
    }

    @Override
    public List<GisAir> queryGisAirMonitorHis(GisMonitorHisDTO gisMonitorHisDTO) {

        return baseMapper.queryGisAirMonitorHis(gisMonitorHisDTO.getBeginTime(), gisMonitorHisDTO.getEndTime());
    }

    @Override
    public List<GisWater> queryGisWaterMonitorHis(GisMonitorHisDTO gisMonitorHisDTO) {
        return baseMapper.queryGisWaterMonitorHis(gisMonitorHisDTO);
    }
}
